package com.aclass.xqx.classscreen.model;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Handler;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.aclass.xqx.classscreen.BaseApplication;
import com.aclass.xqx.classscreen.R;
import com.aclass.xqx.classscreen.bean.API;
import com.aclass.xqx.classscreen.bean.HomeBean;
import com.aclass.xqx.classscreen.bean.LoginBean;
import com.aclass.xqx.classscreen.db.AddData;
import com.aclass.xqx.classscreen.db.CardDao;
import com.aclass.xqx.classscreen.db.CardStudent;
import com.aclass.xqx.classscreen.db.CardTeacher;
import com.aclass.xqx.classscreen.db.Cardnumber;
import com.aclass.xqx.classscreen.db.ClassAlbum;
import com.aclass.xqx.classscreen.db.ClassLabour;
import com.aclass.xqx.classscreen.db.ClassSchedule;
import com.aclass.xqx.classscreen.db.Dynamic;
import com.aclass.xqx.classscreen.db.DynamicSchool;
import com.aclass.xqx.classscreen.db.ReadNews;
import com.aclass.xqx.classscreen.db.StudentNews;
import com.aclass.xqx.classscreen.db.StudentSign;
import com.aclass.xqx.classscreen.service.LocalService;
import com.aclass.xqx.classscreen.service.RemoteService;
import com.aclass.xqx.classscreen.utlis.AppUtlis;
import com.aclass.xqx.classscreen.utlis.AsyncTaskSoapUtil;
import com.aclass.xqx.classscreen.utlis.ClassCalendar;
import com.aclass.xqx.classscreen.utlis.Constant;
import com.aclass.xqx.classscreen.utlis.DialogUtlis;
import com.aclass.xqx.classscreen.utlis.OkhttPost;
import com.aclass.xqx.classscreen.utlis.PrefUtild;
import com.google.gson.Gson;
import com.sunfusheng.marqueeview.MarqueeView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by xqx on 2017/11/14.
 * 主页数据模型
 */

public class MainModel {
    private  Context context;
    private Intent intent=new Intent();
    public MainModel(Context context) {
        this.context = context;
    }
    public void upPackages() throws PackageManager.NameNotFoundException {
        String up = PrefUtild.INSTANCE.getString(context, Constant.GETUP, "");
        if(up.equals("1")){
            String version_id = PrefUtild.INSTANCE.getString(context, "version_id", "");
            String version_mini = PrefUtild.INSTANCE.getString(context, "version_mini", "");
            String packageMas = AppUtlis.packageMas(context);
            int i = AppUtlis.packageCode(context);
            if (version_id.equals(i+"")&&version_mini.equals(packageMas)){
                OkhttPost.Okget(API.UPPACKAES+"?app_no="+android.os.Build.SERIAL+"&version_id="+i+"&sno="+Constant.SNO+"&status=1&version_mini="+packageMas,3,new MainCall());
            }else{
                OkhttPost.Okget(API.UPPACKAES+"?app_no="+android.os.Build.SERIAL+"&version_id="+i+"&sno="+Constant.SNO+"&status=0&version_mini="+packageMas,3,new MainCall());
            }
        }
    }
    //判断当前是否登录
    public  boolean  getIsnamepwd(){
        String username= PrefUtild.INSTANCE.getString(context,"class_no","");
        if (username.isEmpty()){
            return true;
        }
        return false;
    }
    //返回当前总人数
    public int getNumber(){
        BaseApplication.getDaoInstant().clear();
        List<CardStudent> cardStudents = CardDao.queryStudent();
        return cardStudents.size();
    }
    //返回实到人数
    public int getTonum(){
        BaseApplication.getDaoInstant().clear();
        int coun=0;
        List<StudentSign> studentSigns = CardDao.querySign();
        long lMinuts = Long.parseLong(ClassCalendar.getStringMinuts());
        long NMinuts = Long.parseLong(ClassCalendar.getStringDays("12", "00"));
        if (lMinuts<NMinuts) {
            for (StudentSign sign : studentSigns) {
                long time = Long.parseLong(sign.getTime());
                String stringDays = ClassCalendar.getStringDays("06", "00");
                if (time > Long.parseLong(stringDays)) {
                    coun++;
                }
            }
        }else{
            for (StudentSign sign : studentSigns) {
                long time = Long.parseLong(sign.getTime());
                String stringDays = ClassCalendar.getStringDays("13", "00");
                if (time > Long.parseLong(stringDays)) {
                    coun++;
                }
            }
        }
        return coun;
    }

    /**
     * @return
     * 班级值日
     */
    public String ClassLabour(){
        BaseApplication.getDaoInstant().clear();
        String str="";
        List<ClassLabour> classLabours = CardDao.queryLabourWeekId(ClassCalendar.getWeekDays() + "");
        for (ClassLabour labour:classLabours){
            str+=labour.getStudentneme()+" ";
        }
        return str;
    }
    //班级名称
    public String classname(){
        List<CardTeacher> cardTeachers = CardDao.queryTeacher();
        if (cardTeachers.size()!=0) {
            return cardTeachers.get(0).getClassname();
        }
        return "暂无";
    }
    //班主任
    public String classteachername(){
        List<CardTeacher> cardTeachers = CardDao.queryTeacher();
        if (cardTeachers.size()!=0) {
            return cardTeachers.get(0).getTeacher_name();
        }
        return "暂无";
    }
    //登录模块
    public void Login(String name,String pwd){
        String serialNum = android.os.Build.SERIAL;
        Toast.makeText(context,serialNum,Toast.LENGTH_LONG).show();
        Log.e("ATG","设备"+serialNum);
        OkhttPost.Okget(API.LOGIN+"?account_no="+name+"&password="+pwd+"&sno="+Constant.SNO+"&app_no="+serialNum,1,new MainCall());
//        http://smart.gcihjt.com//boardApi/articleLogin?account_no=&password=&sno=
    }
    //删除消息
    public void deleteNews(String id,String Nid,String name,String time,String content){
            PrefUtild.INSTANCE.setString(context,"News","");
            OkhttPost.Deleteget(API.DELETENEWS+"?sno="+Constant.SNO+"&id="+id,Nid,2,new DeleteCall(),id,name,time,content);

    }
    //校园动态
    public String ArtSchool(){
        BaseApplication.getDaoInstant().clear();
        String str="";
        List<DynamicSchool> dynamics = CardDao.queryArtschool();
        if (dynamics.size()!=0) {
            for (DynamicSchool dynamic : dynamics) {
                    str = "1."+dynamic.getTitle();
            }
        }else{
            str="";
        }
        return str;
    }
    //校园动态
    public List<String> ArtSchools(){
        BaseApplication.getDaoInstant().clear();
        List<String> strclass=new ArrayList<>();
        List<DynamicSchool> dynamics = CardDao.queryArtschool();
        if (dynamics.size()!=0) {
            for (DynamicSchool dynamic : dynamics) {
                    String str=dynamic.getContent();
                    strclass = AppUtlis.handleText(str,39,42.5f);
            }
        }else{
            strclass.add("");
        }
        return strclass;
    }
    //班级动态
    public List<String> ArtCalss(){
       List<Dynamic> art_class = CardDao.queryArtClass();
        List<String> strclass=new ArrayList<>();
        if (art_class.size()!=0){
            for (int i=0;i<art_class.size();i++){
                String content=art_class.get(i).getContent();
                strclass = AppUtlis.handleText(content,25,35.5f);
            }
        }else{
            strclass.add("");
        }
        return strclass;
    }

    //打卡考勤
    public void Timecard(String cardNum, AsyncTaskSoapUtil.Callback callback){
        String time=ClassCalendar.getCardtime();
        String str2="<RECORDS version=\"1.2\">\t \n" +
                "<ERRECORD>\n" +
                "<CLOCKID>"+android.os.Build.SERIAL+"</CLOCKID>\n" +
                "<CARDID>"+cardNum+"</CARDID>\n" +
                "<DATETIME>"+time+"</DATETIME> \n" +
                "<BFLAG>2</BFLAG>\n" +
                "</ERRECORD>\n" +
                "</RECORDS>";
        String namespace = "http://www.gcihjt.com/";//namespace
        String methodName = "UploadSwingCards";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        Log.e("debug","JSHJT098000");
        String md5="hjt"+time+"256B07301378445C83CB1A4D021FF4C7";
//        String md51 = AppUtlis.md5(md5);
        String md5Value = AppUtlis.getMd5Value(md5);
        Log.e("debug12",md5Value);
        map.put("Xml",str2);
        map.put("username","hjt");
        map.put("timeStr",time);
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(callback);
        soapUtil.execute();
    }
    //轮播图
    public List<String> ClassBanner(){
        BaseApplication.getDaoInstant().clear();
        List<String> albumbanner=new ArrayList<>();
        List<ClassAlbum> classAlba = CardDao.queryAlbumTid("1");
        if (classAlba.size()!=0){
            if (classAlba.size()<5){
                int j=0;
                for (int i=1;i<6;i++){
                       if (j<classAlba.size()){
                           albumbanner.add(classAlba.get(j).getPic());
                           ++j;
                       }else {
                           j=0;
                       }
                }
            }else{
                for (ClassAlbum album:classAlba){
                    albumbanner.add(album.getPic());
                }
            }

        }
        return albumbanner;
    }
    //班级荣誉
    public List<String> ClassHonor(){
        List<String> albumbanner=new ArrayList<>();
        BaseApplication.getDaoInstant().clear();
        List<ClassAlbum> classAlba = CardDao.queryAlbumTid("2");
        if (classAlba.size()<6){
            for (ClassAlbum album:classAlba){
                albumbanner.add(album.getPic());
            }
        }else{
          for (int i=0;i<6;i++){
              albumbanner.add(classAlba.get(i).getPic());
          }
        }
        return albumbanner;
    }
    //早上课表
    public List<String> ClassScheduleMorning(){
        List<String> list=new ArrayList<>();
        BaseApplication.getDaoInstant().clear();
        List<ClassSchedule> queryschedule = CardDao.queryscheduleWeek((ClassCalendar.getWeekDays()) + "");
        for (ClassSchedule schedule:queryschedule){
            String start_time = schedule.getStart_time();
            if (start_time!=null) {
               int  time = Integer.parseInt(start_time.substring(0, 2));
                if (time<12){
                    String str=schedule.getStart_time()+"-"+schedule.getEnd_time()+" "+schedule.getSubject_name();
                    list.add(str);
                }
            }
        }
        return list;
    }

    //下午课表
    public List<String>  ClassScheduleaFternoon(){
        List<String> list=new ArrayList<>();
        BaseApplication.getDaoInstant().clear();
        List<ClassSchedule> queryschedule = CardDao.queryscheduleWeek((ClassCalendar.getWeekDays()) + "");
        for (ClassSchedule schedule:queryschedule){
            String start_time = schedule.getStart_time();
            if (start_time!=null) {
                int  time = Integer.parseInt(start_time.substring(0, 2));
                if (time>12){
                    String str=schedule.getStart_time()+"-"+schedule.getEnd_time()+" "+schedule.getSubject_name();
                    list.add(str);
                }
            }
        }
        return list;
    }
    //消息模块
    public  String StudentSign(){
        BaseApplication.getDaoInstant().clear();
        List<CardStudent> cardStudents = CardDao.queryStudent();
        if (cardStudents.size()==0){
            return "8";
        }
        String name=context.getString(R.string.studentnews);
        for (CardStudent studet:cardStudents){

            List<StudentNews> newses = studet.getNewses();
            if (newses.size()!=0){
                name += studet.getStudent_name() + " ";
            }
        }
        if (name.equals(context.getString(R.string.studentnews))){
            return "8";
        }
        return name;
    }
    public static String class_no="";
    class MainCall implements OkhttPost.Callback {
        @Override
        public void onError(Call call, Exception e, int id) {
            if (id==1){

                errbroadcast("登录失败 :"+e.toString());
            }else if(id==2){
                errbroadcast("登录失败 :"+e.toString());
            }
        }

        @Override
        public void onResponse(String response, int id) {
            if (id==1){
                try {
                    Gson gson=new Gson();
                    LoginBean bean = gson.fromJson(response, LoginBean.class);
                    if (bean.code==0){
                        Loginbroadcast(Constant.LOGIN,bean.msg,"","1");
                    }else if (bean.code==1){
                        PrefUtild.INSTANCE.setString(context,"class_no","");
                        CardDao.deleteAll();
                        errbroadcast("登录成功");
                        Log.e("ATG",bean.class_no);
                        class_no=bean.class_no;
                        OkhttPost.Okget(API.HOME+Constant.SNO+"/"+bean.class_no+"?app_no="+android.os.Build.SERIAL,2,new MainCall());

                        PrefUtild.INSTANCE.setString(context,Constant.NEWS,"1");
                    }
//                    Log.e("ATG",bean.code+"  "+bean.msg+"  "+bean.school_no+" "+bean.class_no);
                }catch (Exception e){}

            }else if(id==2){
                try {
                    AddData.addCardNum("test1","3428661647",0);
                    AddData.addCardNum("test2","1907098144",0);
                    AddData.addCardNum("test3","1180779457",0);
                    AddData.addCardNum("test4","1136897088",0);
                    AddData.addCardNum("test5","2157230741",0);
//                    Log.e("ATG",response);
                    PrefUtild.INSTANCE.setString(context,"class_no",class_no);
                    Gson gson=new Gson();
                    HomeBean homeBean = gson.fromJson(response, HomeBean.class);
                    List<HomeBean.Class_Info> class_infos=homeBean.class_info;
                    for (HomeBean.Class_Info class_info:class_infos){
                        if (class_info.card_no!=null&&class_info.classname!=null) {
                            AddData.addTeacher(class_info.teacher_no,class_info.card_no,class_info.classname,class_info.teacher_name);
                        }
                    }
                    HomeBean.AppInfo AppInfo=homeBean.app_info;
                    if (AppInfo!=null) {
                        PrefUtild.INSTANCE.setString(context, Constant.ENCRYPTION, AppInfo.is_encryption);
                        PrefUtild.INSTANCE.setString(context, Constant.KEY, AppInfo.key);
                    }
                    List<HomeBean.Class_list> class_lists= homeBean.class_list;
                    for (HomeBean.Class_list list:class_lists){
                        if (list.card_no!=null&&list.student_no!=null){
                            AddData.addStudent(list.student_no,list.card_no,list.name,list.honor_id==null?"0":list.honor_id,list.headimg==null?"无头像":list.headimg);
                        }
                    }
                    List<HomeBean.Lesson_list> lesson_list = homeBean.lesson_list;
                    for (HomeBean.Lesson_list lessonList:lesson_list){
                        if (lessonList.week_day!=null&&lessonList.end_time!=null&&lessonList.start_time!=null
                                &&lessonList.name!=null) {
                            AddData.addSchedule(lessonList.id,lessonList.name,lessonList.week_day,lessonList.start_time,lessonList.end_time);
                        }
                    }
                    List<HomeBean.Art_school> art_school = homeBean.art_school;
                    for (HomeBean.Art_school artSchool:art_school){
                            AddData.addDynamicSchool(artSchool.id,artSchool.add_time,artSchool.content,artSchool.title);
                    }
                    List<HomeBean.Art_class> art_class = homeBean.art_class;
                    for (HomeBean.Art_class artClass:art_class){
                            AddData.addDynamic(artClass.id,artClass.add_time,artClass.content,artClass.title);
                    }
                    List<HomeBean.Album> albums = homeBean.album;
                    for (HomeBean.Album album:albums){
                            AddData.addAlbum(album.id,album.add_time,album.pic_path,album.type_id);
                    }
                    List<HomeBean.Labour_list> labour_list = homeBean.labour_list;
                    for (HomeBean.Labour_list list:labour_list){
                        if (list.week_day!=null&&list.student_name!=null){
                            AddData.addLabour(list.student_id,list.week_day,list.student_name,list.add_time);
                        }
                    }
                    List<HomeBean.Teacher_list> teacher_lists = homeBean.teacher_list;
                    for (HomeBean.Teacher_list teacher_list:teacher_lists){
                        if (teacher_list.card_no!=null){
                            AddData.addCardNum(teacher_list.teacher_no,teacher_list.card_no,2);
                        }
                    }
                    Intent intent=new Intent(context, LocalService.class);
                    context.startService(intent);
                    Intent intent1=new Intent(context, RemoteService.class);
                    context.startService(intent1);
                    Loginbroadcast(Constant.LOGIN,"","","2");
                }catch (Exception e){}

            }else if (id==3){
                 Log.e("ATGS","更新回调接口");
                 PrefUtild.INSTANCE.setString(context, Constant.GETUP, "");
            }
        }
    }
    class DeleteCall implements OkhttPost.DeleteCallback{
        @Override
        public void onError(Call call, Exception e, String nid, int id, String did, String name, String time, String content) {
            errbroadcast("消息模块错误 :"+e.toString());
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    PrefUtild.INSTANCE.setString(context,Constant.NEWS,"1");
                }
            },3000);
        }

        @Override
        public void onResponse(String response, String nid, int id, String did, String name, String time, String content) {
            Log.e("ATG","删除"+response);
            ReadNews readNews=new ReadNews(did,content,time,nid);
            CardDao.insertRead(readNews);
            broadcast(Constant.DELETE);
        }
    }
    //登录广播
    public void Loginbroadcast(String key,String logintype,String err,String type){
        intent.putExtra(key,logintype+" "+err);
        intent.putExtra("type",type);
        broadcast(Constant.LOGIN);
    }
    //调试广播
    public void errbroadcast(String content){
        intent.putExtra(Constant.ERR,content);
        broadcast(Constant.ERR);
    }
    public void broadcast(String action){
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(action);
        context.sendBroadcast(intent);
    }
}
